home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / C / Applications / Python 1.3 / source code / Misc / python-mode.el < prev    next >
Encoding:
Text File  |  1995-12-17  |  76.6 KB  |  2,057 lines  |  [TEXT/R*ch]

  1. ;;; python-mode.el --- Major mode for editing Python programs
  2.  
  3. ;; Copyright (C) 1992,1993,1994  Tim Peters
  4.  
  5. ;; Author: 1995 Barry A. Warsaw
  6. ;;         1992-1994 Tim Peters
  7. ;; Maintainer:    python-mode@python.org
  8. ;; Created:       Feb 1992
  9. ;; Version:       2.30
  10. ;; Last Modified: 1995/09/19 20:01:42
  11. ;; Keywords: python editing language major-mode
  12.  
  13. ;; This software is provided as-is, without express or implied
  14. ;; warranty.  Permission to use, copy, modify, distribute or sell this
  15. ;; software, without fee, for any purpose and by any individual or
  16. ;; organization, is hereby granted, provided that the above copyright
  17. ;; notice and this paragraph appear in all copies.
  18.  
  19. ;;; Commentary:
  20. ;;
  21. ;; This is a major mode for editing Python programs.  It was developed
  22. ;; by Tim Peters <tim@ksr.com> after an original idea by Michael
  23. ;; A. Guravage.  Tim doesn't appear to be on the 'net any longer so I
  24. ;; have undertaken maintenance of the mode.
  25.  
  26. ;; At some point this mode will undergo a rewrite to bring it more in
  27. ;; line with GNU Emacs Lisp coding standards.  But all in all, the
  28. ;; mode works exceedingly well.
  29.  
  30. ;; The following statements, placed in your .emacs file or
  31. ;; site-init.el, will cause this file to be autoloaded, and
  32. ;; python-mode invoked, when visiting .py files (assuming this file is
  33. ;; in your load-path):
  34. ;;
  35. ;;    (autoload 'python-mode "python-mode" "Python editing mode." t)
  36. ;;    (setq auto-mode-alist
  37. ;;          (cons '("\\.py$" . python-mode) auto-mode-alist))
  38.  
  39. ;; Here's a brief list of recent additions/improvements:
  40. ;;
  41. ;; - Wrapping and indentation within triple quote strings should work
  42. ;;   properly now.
  43. ;; - `Standard' bug reporting mechanism (use C-c C-b)
  44. ;; - py-mark-block was moved to C-c C-m
  45. ;; - C-c C-v shows you the python-mode version
  46. ;; - a basic python-font-lock-keywords has been added for Emacs 19
  47. ;;   font-lock colorizations.
  48. ;; - proper interaction with pending-del and del-sel modes.
  49. ;; - New py-electric-colon (:) command for improved outdenting.  Also
  50. ;;   py-indent-line (TAB) should handle outdented lines better.
  51. ;; - New commands py-outdent-left (C-c C-l) and py-indent-right (C-c C-r)
  52.  
  53. ;; Here's a brief to do list:
  54. ;;
  55. ;; - Better integration with gud-mode for debugging.
  56. ;; - Rewrite according to GNU Emacs Lisp standards.
  57. ;; - py-delete-char should obey numeric arguments.
  58. ;; - even better support for outdenting.  Guido suggests outdents of
  59. ;;   at least one level after a return, raise, break, or continue
  60. ;;   statement.
  61. ;; - de-electrify colon inside literals (e.g. comments and strings)
  62.  
  63. ;; If you can think of more things you'd like to see, drop me a line.
  64. ;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
  65. ;;
  66. ;; Note that I only test things on XEmacs (currently 19.11).  If you
  67. ;; port stuff to FSF Emacs 19, or Emacs 18, please send me your
  68. ;; patches.
  69.  
  70. ;; LCD Archive Entry:
  71. ;; python-mode|Barry A. Warsaw|python-mode@python.org
  72. ;; |Major mode for editing Python programs
  73. ;; |1995/09/19 20:01:42|2.30|
  74.  
  75. ;;; Code:
  76.  
  77.  
  78. ;; user definable variables
  79. ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
  80.  
  81. (defvar py-python-command "python"
  82.   "*Shell command used to start Python interpreter.")
  83.  
  84. (defvar py-indent-offset 8        ; argue with Guido <grin>
  85.   "*Indentation increment.
  86. Note that `\\[py-guess-indent-offset]' can usually guess a good value
  87. when you're editing someone else's Python code.")
  88.  
  89. (defvar py-align-multiline-strings-p t
  90.   "*Flag describing how multiline triple quoted strings are aligned.
  91. When this flag is non-nil, continuation lines are lined up under the
  92. preceding line's indentation.  When this flag is nil, continuation
  93. lines are aligned to column zero.")
  94.  
  95. (defvar py-block-comment-prefix "##"
  96.   "*String used by `py-comment-region' to comment out a block of code.
  97. This should follow the convention for non-indenting comment lines so
  98. that the indentation commands won't get confused (i.e., the string
  99. should be of the form `#x...' where `x' is not a blank or a tab, and
  100. `...' is arbitrary).")
  101.  
  102. (defvar py-scroll-process-buffer t
  103.   "*Scroll Python process buffer as output arrives.
  104. If nil, the Python process buffer acts, with respect to scrolling, like
  105. Shell-mode buffers normally act.  This is surprisingly complicated and
  106. so won't be explained here; in fact, you can't get the whole story
  107. without studying the Emacs C code.
  108.  
  109. If non-nil, the behavior is different in two respects (which are
  110. slightly inaccurate in the interest of brevity):
  111.  
  112.   - If the buffer is in a window, and you left point at its end, the
  113.     window will scroll as new output arrives, and point will move to the
  114.     buffer's end, even if the window is not the selected window (that
  115.     being the one the cursor is in).  The usual behavior for shell-mode
  116.     windows is not to scroll, and to leave point where it was, if the
  117.     buffer is in a window other than the selected window.
  118.  
  119.   - If the buffer is not visible in any window, and you left point at
  120.     its end, the buffer will be popped into a window as soon as more
  121.     output arrives.  This is handy if you have a long-running
  122.     computation and don't want to tie up screen area waiting for the
  123.     output.  The usual behavior for a shell-mode buffer is to stay
  124.     invisible until you explicitly visit it.
  125.  
  126. Note the `and if you left point at its end' clauses in both of the
  127. above:  you can `turn off' the special behaviors while output is in
  128. progress, by visiting the Python buffer and moving point to anywhere
  129. besides the end.  Then the buffer won't scroll, point will remain where
  130. you leave it, and if you hide the buffer it will stay hidden until you
  131. visit it again.  You can enable and disable the special behaviors as
  132. often as you like, while output is in progress, by (respectively) moving
  133. point to, or away from, the end of the buffer.
  134.  
  135. Warning:  If you expect a large amount of output, you'll probably be
  136. happier setting this option to nil.
  137.  
  138. Obscure:  `End of buffer' above should really say `at or beyond the
  139. process mark', but if you know what that means you didn't need to be
  140. told <grin>.")
  141.  
  142. (defvar py-temp-directory
  143.   (let ((ok '(lambda (x)
  144.            (and x
  145.             (setq x (expand-file-name x)) ; always true
  146.             (file-directory-p x)
  147.             (file-writable-p x)
  148.             x))))
  149.     (or (funcall ok (getenv "TMPDIR"))
  150.     (funcall ok "/usr/tmp")
  151.     (funcall ok "/tmp")
  152.     (funcall ok  ".")
  153.     (error
  154.      "Couldn't find a usable temp directory -- set py-temp-directory")))
  155.   "*Directory used for temp files created by a *Python* process.
  156. By default, the first directory from this list that exists and that you
  157. can write into:  the value (if any) of the environment variable TMPDIR,
  158. /usr/tmp, /tmp, or the current directory.")
  159.  
  160. (defvar py-beep-if-tab-change t
  161.   "*Ring the bell if tab-width is changed.
  162. If a comment of the form
  163.  
  164.   \t# vi:set tabsize=<number>:
  165.  
  166. is found before the first code line when the file is entered, and the
  167. current value of (the general Emacs variable) `tab-width' does not
  168. equal <number>, `tab-width' is set to <number>, a message saying so is
  169. displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
  170. the Emacs bell is also rung as a warning.")
  171.  
  172. ;; These were the previous font-lock keywords, but I think I now
  173. ;; prefer the ones from XEmacs 19.12's font-lock.el.  I've merged the
  174. ;; two into the new definition below.
  175. ;;
  176. ;;(defvar python-font-lock-keywords
  177. ;;  (list
  178. ;;   (cons
  179. ;;    (concat
  180. ;;     "\\<\\("
  181. ;;     (mapconcat
  182. ;;      'identity
  183. ;;      '("access"  "and"      "break"  "continue"
  184. ;;    "del"     "elif"     "else"   "except"
  185. ;;    "exec"    "finally"  "for"    "from"
  186. ;;    "global"  "if"       "import" "in"
  187. ;;    "is"      "lambda"   "not"    "or"
  188. ;;    "pass"    "print"    "raise"  "return"
  189. ;;    "try"     "while"    "def"    "class"
  190. ;;    )
  191. ;;      "\\|")
  192. ;;     "\\)\\>")
  193. ;;    1)
  194. ;;   ;; functions
  195. ;;   '("\\bdef\\s +\\(\\sw+\\)(" 1 font-lock-function-name-face)
  196. ;;   ;; classes
  197. ;;   '("\\bclass\\s +\\(\\sw+\\)[(:]" 1 font-lock-function-name-face)
  198. ;;   )
  199. ;;  "*Additional keywords to highlight `python-mode' buffers.")
  200.  
  201. ;; These are taken from XEmacs 19.12's font-lock.el file, but have the
  202. ;; more complete list of keywords from the previous definition in
  203. ;; python-mode.el.  There are a few other minor stylistic changes as
  204. ;; well.
  205. ;; 
  206. (defvar python-font-lock-keywords
  207.    (list
  208.     (cons (concat
  209.        "\\b\\("
  210.        (mapconcat
  211.         'identity
  212.         '("access"     "and"      "break"    "continue"
  213.           "del"        "elif"     "else:"    "except"
  214.           "except:"    "exec"     "finally:" "for"
  215.           "from"       "global"   "if"       "import"
  216.           "in"         "is"       "lambda"   "not"
  217.           "or"         "pass"     "print"    "raise"
  218.           "return"     "try:"     "while"
  219.           )
  220.         "\\|")
  221.        "\\)[ \n\t(]")
  222.           1)
  223.     ;; classes
  224.     '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
  225.       1 font-lock-type-face)
  226.     ;; functions
  227.     '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
  228.       1 font-lock-function-name-face)
  229.     )
  230.   "*Additional expressions to highlight in Python mode.")
  231.  
  232. ;; R Lindsay Todd <toddr@rpi.edu> suggests these changes to the
  233. ;; original keywords, which wouldn't be necessary if we go with the
  234. ;; XEmacs defaults, but which I agree makes sense without them.
  235. ;;
  236. ;; functions
  237. ;; '("\\bdef\\s +\\(\\sw+\\)\\s *(" 1 font-lock-function-name-face)
  238. ;; classes
  239. ;; '("\\bclass\\s +\\(\\sw+\\)\\s *[(:]" 1 font-lock-type-face)
  240.  
  241.  
  242.  
  243. ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  244. ;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
  245.  
  246. ;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19.  This
  247. ;; seems to be the standard way of checking this.
  248. ;; BAW - This is *not* the right solution.  When at all possible,
  249. ;; instead of testing for the version of Emacs, use feature tests.
  250.  
  251. (setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
  252. (setq py-this-is-emacs-19-p
  253.       (and
  254.        (not py-this-is-lucid-emacs-p)
  255.        (string-match "^19\\." emacs-version)))
  256.  
  257. ;; have to bind py-file-queue before installing the kill-emacs hook
  258. (defvar py-file-queue nil
  259.   "Queue of Python temp files awaiting execution.
  260. Currently-active file is at the head of the list.")
  261.  
  262. ;; define a mode-specific abbrev table for those who use such things
  263. (defvar python-mode-abbrev-table nil
  264.   "Abbrev table in use in `python-mode' buffers.")
  265. (define-abbrev-table 'python-mode-abbrev-table nil)
  266.  
  267. (defvar python-mode-hook nil
  268.   "*Hook called by `python-mode'.")
  269.  
  270. ;; in previous version of python-mode.el, the hook was incorrectly
  271. ;; called py-mode-hook, and was not defvar'd.  deprecate its use.
  272. (and (fboundp 'make-obsolete-variable)
  273.      (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
  274.  
  275. (defvar py-mode-map ()
  276.   "Keymap used in `python-mode' buffers.")
  277.  
  278. (if py-mode-map
  279.     ()
  280.   (setq py-mode-map (make-sparse-keymap))
  281.  
  282.   ;; shadow global bindings for newline-and-indent w/ the py- version.
  283.   ;; BAW - this is extremely bad form, but I'm not going to change it
  284.   ;; for now.
  285.   (mapcar (function (lambda (key)
  286.               (define-key
  287.             py-mode-map key 'py-newline-and-indent)))
  288.    (where-is-internal 'newline-and-indent))
  289.  
  290.   ;; BAW - you could do it this way, but its not considered proper
  291.   ;; major-mode form.
  292.   (mapcar (function
  293.        (lambda (x)
  294.          (define-key py-mode-map (car x) (cdr x))))
  295.       '((":"         . py-electric-colon)
  296.         ("\C-c\C-c"  . py-execute-buffer)
  297.         ("\C-c|"     . py-execute-region)
  298.         ("\C-c!"     . py-shell)
  299.         ("\177"     . py-delete-char)
  300.         ("\n"     . py-newline-and-indent)
  301.         ("\C-c:"     . py-guess-indent-offset)
  302.         ("\C-c\t"     . py-indent-region)
  303.         ("\C-c\C-l"  . py-outdent-left)
  304.         ("\C-c\C-r"  . py-indent-right)
  305.         ("\C-c<"     . py-shift-region-left)
  306.         ("\C-c>"     . py-shift-region-right)
  307.         ("\C-c\C-n"  . py-next-statement)
  308.         ("\C-c\C-p"  . py-previous-statement)
  309.         ("\C-c\C-u"  . py-goto-block-up)
  310.         ("\C-c\C-m"  . py-mark-block)
  311.         ("\C-c#"     . py-comment-region)
  312.         ("\C-c?"     . py-describe-mode)
  313.         ("\C-c\C-hm" . py-describe-mode)
  314.         ("\e\C-a"     . beginning-of-python-def-or-class)
  315.         ("\e\C-e"     . end-of-python-def-or-class)
  316.         ( "\e\C-h"     . mark-python-def-or-class)))
  317.   ;; should do all keybindings this way
  318.   (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
  319.   (define-key py-mode-map "\C-c\C-v" 'py-version)
  320.   )
  321.  
  322. (defvar py-mode-syntax-table nil
  323.   "Syntax table used in `python-mode' buffers.")
  324.  
  325. (if py-mode-syntax-table
  326.     ()
  327.   (setq py-mode-syntax-table (make-syntax-table))
  328.   ;; BAW - again, blech.
  329.   (mapcar (function
  330.        (lambda (x) (modify-syntax-entry
  331.             (car x) (cdr x) py-mode-syntax-table)))
  332.       '(( ?\( . "()" ) ( ?\) . ")(" )
  333.         ( ?\[ . "(]" ) ( ?\] . ")[" )
  334.         ( ?\{ . "(}" ) ( ?\} . "){" )
  335.         ;; fix operator symbols misassigned in the std table
  336.         ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
  337.         ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
  338.         ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
  339.         ( ?\> . "." ) ( ?\| . "." )
  340.         ( ?\_ . "w" )    ; underscore is legit in names
  341.         ( ?\' . "\"")    ; single quote is string quote
  342.         ( ?\" . "\"" )    ; double quote is string quote too
  343.         ( ?\` . "$")    ; backquote is open and close paren
  344.         ( ?\# . "<")    ; hash starts comment
  345.         ( ?\n . ">"))))    ; newline ends comment
  346.  
  347. (defconst py-stringlit-re
  348.   (concat
  349.    "'\\([^'\n\\]\\|\\\\.\\)*'"        ; single-quoted
  350.    "\\|"                ; or
  351.    "\"\\([^\"\n\\]\\|\\\\.\\)*\"")    ; double-quoted
  352.   "Regexp matching a Python string literal.")
  353.  
  354. ;; this is tricky because a trailing backslash does not mean
  355. ;; continuation if it's in a comment
  356. (defconst py-continued-re
  357.   (concat
  358.    "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
  359.    "\\\\$")
  360.   "Regexp matching Python lines that are continued via backslash.")
  361.  
  362. (defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
  363.   "Regexp matching blank or comment lines.")
  364.  
  365. (defconst py-outdent-re
  366.   (concat "\\(" (mapconcat 'identity
  367.                '("else:"
  368.                  "except\\(\\s +.*\\)?:"
  369.                  "finally:"
  370.                  "elif\\s +.*:")
  371.                "\\|")
  372.       "\\)")
  373.   "Regexp matching clauses to be outdented one level.")
  374.  
  375. (defconst py-no-outdent-re
  376.   (concat "\\(" (mapconcat 'identity
  377.                '("try:"
  378.                  "except\\(\\s +.*\\)?:"
  379.                  "while\\s +.*:"
  380.                  "for\\s +.*:"
  381.                  "if\\s +.*:"
  382.                  "elif\\s +.*:")
  383.                "\\|")
  384.       "\\)")
  385.   "Regexp matching lines to not outdent after.")
  386.  
  387.  
  388. ;;;###autoload
  389. (defun python-mode ()
  390.   "Major mode for editing Python files.
  391. To submit a problem report, enter `\\[py-submit-bug-report]' from a
  392. `python-mode' buffer.  Do `\\[py-describe-mode]' for detailed
  393. documentation.  To see what version of `python-mode' you are running,
  394. enter `\\[py-version]'.
  395.  
  396. This mode knows about Python indentation, tokens, comments and
  397. continuation lines.  Paragraphs are separated by blank lines only.
  398.  
  399. COMMANDS
  400. \\{py-mode-map}
  401. VARIABLES
  402.  
  403. py-indent-offset\tindentation increment
  404. py-block-comment-prefix\tcomment string used by py-comment-region
  405. py-python-command\tshell command to invoke Python interpreter
  406. py-scroll-process-buffer\talways scroll Python process buffer
  407. py-temp-directory\tdirectory used for temp files (if needed)
  408. py-beep-if-tab-change\tring the bell if tab-width is changed"
  409.   (interactive)
  410.   (kill-all-local-variables)
  411.   (set-syntax-table py-mode-syntax-table)
  412.   (setq major-mode 'python-mode
  413.     mode-name "Python"
  414.     local-abbrev-table python-mode-abbrev-table)
  415.   (use-local-map py-mode-map)
  416.   ;; Emacs 19 requires this
  417.   (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
  418.       (setq comment-multi-line nil))
  419.   ;; BAW -- style...
  420.   (mapcar (function (lambda (x)
  421.               (make-local-variable (car x))
  422.               (set (car x) (cdr x))))
  423.       '((paragraph-separate . "^[ \t]*$")
  424.         (paragraph-start     . "^[ \t]*$")
  425.         (require-final-newline . t)
  426.         (comment-start .        "# ")
  427.         (comment-start-skip .    "# *")
  428.         (comment-column . 40)
  429.         (indent-region-function . py-indent-region)
  430.         (indent-line-function . py-indent-line)))
  431.   ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
  432.   ;;
  433.   ;; not sure where the magic comment has to be; to save time
  434.   ;; searching for a rarity, we give up if it's not found prior to the
  435.   ;; first executable statement.
  436.   ;;
  437.   ;; BAW - on first glance, this seems like complete hackery.  Why was
  438.   ;; this necessary, and is it still necessary?
  439.   (let ((case-fold-search nil)
  440.     (start (point))
  441.     new-tab-width)
  442.     (if (re-search-forward
  443.      "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
  444.      (prog2 (py-next-statement 1) (point) (goto-char 1))
  445.      t)
  446.     (progn
  447.       (setq new-tab-width
  448.         (string-to-int
  449.          (buffer-substring (match-beginning 1) (match-end 1))))
  450.       (if (= tab-width new-tab-width)
  451.           nil
  452.         (setq tab-width new-tab-width)
  453.         (message "Caution: tab-width changed to %d" new-tab-width)
  454.         (if py-beep-if-tab-change (beep)))))
  455.     (goto-char start))
  456.  
  457.   ;; run the mode hook. py-mode-hook use is deprecated
  458.   (if python-mode-hook
  459.       (run-hooks 'python-mode-hook)
  460.     (run-hooks 'py-mode-hook)))
  461.  
  462.  
  463. ;; electric characters
  464. (defun py-outdent-p ()
  465.   ;; returns non-nil if the current line should outdent one level
  466.   (save-excursion
  467.     (and (progn (back-to-indentation)
  468.         (looking-at py-outdent-re))
  469.      (progn (backward-to-indentation 1)
  470.         (while (or (looking-at py-blank-or-comment-re)
  471.                (bobp))
  472.           (backward-to-indentation 1))
  473.         (not (looking-at py-no-outdent-re)))
  474.      )))
  475.       
  476.  
  477. (defun py-electric-colon (arg)
  478.   "Insert a colon.
  479. In certain cases the line is outdented appropriately.  If a numeric
  480. argument is provided, that many colons are inserted non-electrically.
  481. Electric behavior is inhibited inside a string or comment."
  482.   (interactive "P")
  483.   (self-insert-command (prefix-numeric-value arg))
  484.   ;; are we in a string or comment?
  485.   (if (save-excursion
  486.     (let ((pps (parse-partial-sexp (save-excursion
  487.                      (beginning-of-python-def-or-class)
  488.                      (point))
  489.                        (point))))
  490.       (not (or (nth 3 pps) (nth 4 pps)))))
  491.       (save-excursion
  492.     (let ((here (point))
  493.           (outdent 0)
  494.           (indent (py-compute-indentation)))
  495.       (if (and (not arg)
  496.            (py-outdent-p)
  497.            (= indent (save-excursion
  498.                    (forward-line -1)
  499.                    (py-compute-indentation)))
  500.            )
  501.           (setq outdent py-indent-offset))
  502.       ;; Don't indent, only outdent.  This assumes that any lines that
  503.       ;; are already outdented relative to py-compute-indentation were
  504.       ;; put there on purpose.  Its highly annoying to have `:' indent
  505.       ;; for you.  Use TAB, C-c C-l or C-c C-r to adjust.  TBD: Is
  506.       ;; there a better way to determine this???
  507.       (if (< (current-indentation) indent) nil
  508.         (goto-char here)
  509.         (beginning-of-line)
  510.         (delete-horizontal-space)
  511.         (indent-to (- indent outdent))
  512.         )))))
  513.  
  514. (defun py-indent-right (arg)
  515.   "Indent the line by one `py-indent-offset' level.
  516. With numeric arg, indent by that many levels.  You cannot indent
  517. farther right than the distance the line would be indented by
  518. \\[py-indent-line]."
  519.   (interactive "p")
  520.   (let ((col (current-indentation))
  521.     (want (* arg py-indent-offset))
  522.     (indent (py-compute-indentation))
  523.     (pos (- (point-max) (point)))
  524.     (bol (save-excursion (beginning-of-line) (point))))
  525.     (if (<= (+ col want) indent)
  526.     (progn
  527.       (beginning-of-line)
  528.       (delete-horizontal-space)
  529.       (indent-to (+ col want))
  530.       (if (> (- (point-max) pos) (point))
  531.           (goto-char (- (point-max) pos)))
  532.       ))))
  533.  
  534. (defun py-outdent-left (arg)
  535.   "Outdent the line by one `py-indent-offset' level.
  536. With numeric arg, outdent by that many levels.  You cannot outdent
  537. farther left than column zero."
  538.   (interactive "p")
  539.   (let ((col (current-indentation))
  540.     (want (* arg py-indent-offset))
  541.     (pos (- (point-max) (point)))
  542.     (bol (save-excursion (beginning-of-line) (point))))
  543.     (if (<= 0 (- col want))
  544.     (progn
  545.       (beginning-of-line)
  546.       (delete-horizontal-space)
  547.       (indent-to (- col want))
  548.       (if (> (- (point-max) pos) (point))
  549.           (goto-char (- (point-max) pos)))
  550.       ))))
  551.  
  552.  
  553. ;;; Functions that execute Python commands in a subprocess
  554. (defun py-shell ()
  555.   "Start an interactive Python interpreter in another window.
  556. This is like Shell mode, except that Python is running in the window
  557. instead of a shell.  See the `Interactive Shell' and `Shell Mode'
  558. sections of the Emacs manual for details, especially for the key
  559. bindings active in the `*Python*' buffer.
  560.  
  561. See the docs for variable `py-scroll-buffer' for info on scrolling
  562. behavior in the process window.
  563.  
  564. Warning: Don't use an interactive Python if you change sys.ps1 or
  565. sys.ps2 from their default values, or if you're running code that
  566. prints `>>> ' or `... ' at the start of a line.  `python-mode' can't
  567. distinguish your output from Python's output, and assumes that `>>> '
  568. at the start of a line is a prompt from Python.  Similarly, the Emacs
  569. Shell mode code assumes that both `>>> ' and `... ' at the start of a
  570. line are Python prompts.  Bad things can happen if you fool either
  571. mode.
  572.  
  573. Warning:  If you do any editing *in* the process buffer *while* the
  574. buffer is accepting output from Python, do NOT attempt to `undo' the
  575. changes.  Some of the output (nowhere near the parts you changed!) may
  576. be lost if you do.  This appears to be an Emacs bug, an unfortunate
  577. interaction between undo and process filters; the same problem exists in
  578. non-Python process buffers using the default (Emacs-supplied) process
  579. filter."
  580.   ;; BAW - should undo be disabled in the python process buffer, if
  581.   ;; this bug still exists?
  582.   (interactive)
  583.   (if py-this-is-emacs-19-p
  584.       (progn
  585.     (require 'comint)
  586.     (switch-to-buffer-other-window
  587.      (make-comint "Python" py-python-command)))
  588.     (progn
  589.       (require 'shell)
  590.       (switch-to-buffer-other-window
  591.        (apply (if (boundp 'make-shell) 'make-shell 'make-comint)
  592.           "Python" py-python-command nil))))
  593.   (make-local-variable 'shell-prompt-pattern)
  594.   (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
  595.   (set-process-filter (get-buffer-process (current-buffer))
  596.               'py-process-filter)
  597.   (set-syntax-table py-mode-syntax-table))
  598.  
  599. (defun py-execute-region (start end)
  600.   "Send the region between START and END to a Python interpreter.
  601. If there is a *Python* process it is used.
  602.  
  603. Hint: If you want to execute part of a Python file several times
  604. \(e.g., perhaps you're developing a function and want to flesh it out
  605. a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
  606. the region of interest, and send the code to a *Python* process via
  607. `\\[py-execute-buffer]' instead.
  608.  
  609. Following are subtleties to note when using a *Python* process:
  610.  
  611. If a *Python* process is used, the region is copied into a temporary
  612. file (in directory `py-temp-directory'), and an `execfile' command is
  613. sent to Python naming that file.  If you send regions faster than
  614. Python can execute them, `python-mode' will save them into distinct
  615. temp files, and execute the next one in the queue the next time it
  616. sees a `>>> ' prompt from Python.  Each time this happens, the process
  617. buffer is popped into a window (if it's not already in some window) so
  618. you can see it, and a comment of the form
  619.  
  620.   \t## working on region in file <name> ...
  621.  
  622. is inserted at the end.
  623.  
  624. Caution: No more than 26 regions can be pending at any given time.
  625. This limit is (indirectly) inherited from libc's mktemp(3).
  626. `python-mode' does not try to protect you from exceeding the limit.
  627. It's extremely unlikely that you'll get anywhere close to the limit in
  628. practice, unless you're trying to be a jerk <grin>.
  629.  
  630. See the `\\[py-shell]' docs for additional warnings."
  631.   (interactive "r")
  632.   (or (< start end) (error "Region is empty"))
  633.   (let ((pyproc (get-process "Python"))
  634.     fname)
  635.     (if (null pyproc)
  636.     (shell-command-on-region start end py-python-command)
  637.       ;; else feed it thru a temp file
  638.       (setq fname (py-make-temp-name))
  639.       (write-region start end fname nil 'no-msg)
  640.       (setq py-file-queue (append py-file-queue (list fname)))
  641.       (if (cdr py-file-queue)
  642.       (message "File %s queued for execution" fname)
  643.     ;; else
  644.     (py-execute-file pyproc fname)))))
  645.  
  646. (defun py-execute-file (pyproc fname)
  647.   (py-append-to-process-buffer
  648.    pyproc
  649.    (format "## working on region in file %s ...\n" fname))
  650.   (process-send-string pyproc (format "execfile('%s')\n" fname)))
  651.  
  652. (defun py-process-filter (pyproc string)
  653.   (let ((curbuf (current-buffer))
  654.     (pbuf (process-buffer pyproc))
  655.     (pmark (process-mark pyproc))
  656.     file-finished)
  657.  
  658.     ;; make sure we switch to a different buffer at least once.  if we
  659.     ;; *don't* do this, then if the process buffer is in the selected
  660.     ;; window, and point is before the end, and lots of output is
  661.     ;; coming at a fast pace, then (a) simple cursor-movement commands
  662.     ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
  663.     ;; to have a visible effect (the window just doesn't get updated,
  664.     ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
  665.     ;; get all the process output (until the next python prompt).
  666.     ;;
  667.     ;; #b makes no sense to me at all.  #a almost makes sense: unless
  668.     ;; we actually change buffers, set_buffer_internal in buffer.c
  669.     ;; doesn't set windows_or_buffers_changed to 1, & that in turn
  670.     ;; seems to make the Emacs command loop reluctant to update the
  671.     ;; display.  Perhaps the default process filter in process.c's
  672.     ;; read_process_output has update_mode_lines++ for a similar
  673.     ;; reason?  beats me ...
  674.  
  675.     ;; BAW - we want to check to see if this still applies
  676.     (if (eq curbuf pbuf)        ; mysterious ugly hack
  677.     (set-buffer (get-buffer-create "*scratch*")))
  678.  
  679.     (set-buffer pbuf)
  680.     (let* ((start (point))
  681.        (goback (< start pmark))
  682.        (goend (and (not goback) (= start (point-max))))
  683.        (buffer-read-only nil))
  684.       (goto-char pmark)
  685.       (insert string)
  686.       (move-marker pmark (point))
  687.       (setq file-finished
  688.         (and py-file-queue
  689.          (equal ">>> "
  690.             (buffer-substring
  691.              (prog2 (beginning-of-line) (point)
  692.                 (goto-char pmark))
  693.              (point)))))
  694.       (if goback (goto-char start)
  695.     ;; else
  696.     (if py-scroll-process-buffer
  697.         (let* ((pop-up-windows t)
  698.            (pwin (display-buffer pbuf)))
  699.           (set-window-point pwin (point)))))
  700.       (set-buffer curbuf)
  701.       (if file-finished
  702.       (progn
  703.         (py-delete-file-silently (car py-file-queue))
  704.         (setq py-file-queue (cdr py-file-queue))
  705.         (if py-file-queue
  706.         (py-execute-file pyproc (car py-file-queue)))))
  707.       (and goend
  708.        (progn (set-buffer pbuf)
  709.           (goto-char (point-max))))
  710.       )))
  711.  
  712. (defun py-execute-buffer ()
  713.   "Send the contents of the buffer to a Python interpreter.
  714. If there is a *Python* process buffer it is used.  If a clipping
  715. restriction is in effect, only the accessible portion of the buffer is
  716. sent.  A trailing newline will be supplied if needed.
  717.  
  718. See the `\\[py-execute-region]' docs for an account of some subtleties."
  719.   (interactive)
  720.   (py-execute-region (point-min) (point-max)))
  721.  
  722.  
  723.  
  724. ;; Functions for Python style indentation
  725. (defun py-delete-char ()
  726.   "Reduce indentation or delete character.
  727. If point is at the leftmost column, deletes the preceding newline.
  728.  
  729. Else if point is at the leftmost non-blank character of a line that is
  730. neither a continuation line nor a non-indenting comment line, or if
  731. point is at the end of a blank line, reduces the indentation to match
  732. that of the line that opened the current block of code.  The line that
  733. opened the block is displayed in the echo area to help you keep track
  734. of where you are.
  735.  
  736. Else the preceding character is deleted, converting a tab to spaces if
  737. needed so that only a single column position is deleted."
  738.   (interactive "*")
  739.   (if (or (/= (current-indentation) (current-column))
  740.       (bolp)
  741.       (py-continuation-line-p)
  742.       (looking-at "#[^ \t\n]"))    ; non-indenting #
  743.       (backward-delete-char-untabify 1)
  744.     ;; else indent the same as the colon line that opened the block
  745.  
  746.     ;; force non-blank so py-goto-block-up doesn't ignore it
  747.     (insert-char ?* 1)
  748.     (backward-char)
  749.     (let ((base-indent 0)        ; indentation of base line
  750.       (base-text "")        ; and text of base line
  751.       (base-found-p nil))
  752.       (condition-case nil        ; in case no enclosing block
  753.       (save-excursion
  754.         (py-goto-block-up 'no-mark)
  755.         (setq base-indent (current-indentation)
  756.           base-text   (py-suck-up-leading-text)
  757.           base-found-p t))
  758.     (error nil))
  759.       (delete-char 1)            ; toss the dummy character
  760.       (delete-horizontal-space)
  761.       (indent-to base-indent)
  762.       (if base-found-p
  763.       (message "Closes block: %s" base-text)))))
  764.  
  765. ;; required for pending-del and delsel modes
  766. (put 'py-delete-char 'delete-selection 'supersede)
  767. (put 'py-delete-char 'pending-delete   'supersede)
  768.  
  769. (defun py-indent-line ()
  770.   "Fix the indentation of the current line according to Python rules."
  771.   (interactive)
  772.   (let* ((ci (current-indentation))
  773.      (move-to-indentation-p (<= (current-column) ci))
  774.      (need (py-compute-indentation)))
  775.     ;; see if we need to outdent
  776.     (if (py-outdent-p)
  777.     (setq need (- need py-indent-offset)))
  778.     (if (/= ci need)
  779.     (save-excursion
  780.       (beginning-of-line)
  781.       (delete-horizontal-space)
  782.       (indent-to need)))
  783.     (if move-to-indentation-p (back-to-indentation))))
  784.  
  785. (defun py-newline-and-indent ()
  786.   "Strives to act like the Emacs `newline-and-indent'.
  787. This is just `strives to' because correct indentation can't be computed
  788. from scratch for Python code.  In general, deletes the whitespace before
  789. point, inserts a newline, and takes an educated guess as to how you want
  790. the new line indented."
  791.   (interactive)
  792.   (let ((ci (current-indentation)))
  793.     (if (< ci (current-column))        ; if point beyond indentation
  794.     (newline-and-indent)
  795.       ;; else try to act like newline-and-indent "normally" acts
  796.       (beginning-of-line)
  797.       (insert-char ?\n 1)
  798.       (move-to-column ci))))
  799.  
  800. (defun py-compute-indentation ()
  801.   (save-excursion
  802.     (let ((pps (parse-partial-sexp (save-excursion
  803.                      (beginning-of-python-def-or-class)
  804.                      (point))
  805.                    (point))))
  806.       (beginning-of-line)
  807.       (cond
  808.        ;; are we inside a string or comment?
  809.        ((or (nth 3 pps) (nth 4 pps))
  810.     (save-excursion
  811.       (if (not py-align-multiline-strings-p) 0
  812.         ;; skip back over blank & non-indenting comment lines
  813.         ;; note: will skip a blank or non-indenting comment line
  814.         ;; that happens to be a continuation line too
  815.         (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
  816.         (back-to-indentation)
  817.         (current-column))))
  818.        ;; are we on a continuation line?
  819.        ((py-continuation-line-p)
  820.     (let ((startpos (point))
  821.           (open-bracket-pos (py-nesting-level))
  822.           endpos searching found)
  823.       (if open-bracket-pos
  824.           (progn
  825.         ;; align with first item in list; else a normal
  826.         ;; indent beyond the line with the open bracket
  827.         (goto-char (1+ open-bracket-pos)) ; just beyond bracket
  828.         ;; is the first list item on the same line?
  829.         (skip-chars-forward " \t")
  830.         (if (null (memq (following-char) '(?\n ?# ?\\)))
  831.                     ; yes, so line up with it
  832.             (current-column)
  833.           ;; first list item on another line, or doesn't exist yet
  834.           (forward-line 1)
  835.           (while (and (< (point) startpos)
  836.                   (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
  837.             (forward-line 1))
  838.           (if (< (point) startpos)
  839.               ;; again mimic the first list item
  840.               (current-indentation)
  841.             ;; else they're about to enter the first item
  842.             (goto-char open-bracket-pos)
  843.             (+ (current-indentation) py-indent-offset))))
  844.  
  845.         ;; else on backslash continuation line
  846.         (forward-line -1)
  847.         (if (py-continuation-line-p) ; on at least 3rd line in block
  848.         (current-indentation)    ; so just continue the pattern
  849.           ;; else started on 2nd line in block, so indent more.
  850.           ;; if base line is an assignment with a start on a RHS,
  851.           ;; indent to 2 beyond the leftmost "="; else skip first
  852.           ;; chunk of non-whitespace characters on base line, + 1 more
  853.           ;; column
  854.           (end-of-line)
  855.           (setq endpos (point)  searching t)
  856.           (back-to-indentation)
  857.           (setq startpos (point))
  858.           ;; look at all "=" from left to right, stopping at first
  859.           ;; one not nested in a list or string
  860.           (while searching
  861.         (skip-chars-forward "^=" endpos)
  862.         (if (= (point) endpos)
  863.             (setq searching nil)
  864.           (forward-char 1)
  865.           (setq state (parse-partial-sexp startpos (point)))
  866.           (if (and (zerop (car state)) ; not in a bracket
  867.                (null (nth 3 state))) ; & not in a string
  868.               (progn
  869.             (setq searching nil) ; done searching in any case
  870.             (setq found
  871.                   (not (or
  872.                     (eq (following-char) ?=)
  873.                     (memq (char-after (- (point) 2))
  874.                       '(?< ?> ?!)))))))))
  875.           (if (or (not found)    ; not an assignment
  876.               (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
  877.           (progn
  878.             (goto-char startpos)
  879.             (skip-chars-forward "^ \t\n")))
  880.           (1+ (current-column))))))
  881.  
  882.        ;; not on a continuation line
  883.  
  884.        ;; if at start of restriction, or on a non-indenting comment
  885.        ;; line, assume they intended whatever's there
  886.        ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
  887.     (current-indentation))
  888.  
  889.        ;; else indentation based on that of the statement that
  890.        ;; precedes us; use the first line of that statement to
  891.        ;; establish the base, in case the user forced a non-std
  892.        ;; indentation for the continuation lines (if any)
  893.        (t
  894.     ;; skip back over blank & non-indenting comment lines note:
  895.     ;; will skip a blank or non-indenting comment line that
  896.     ;; happens to be a continuation line too
  897.     (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
  898.     ;; if we landed inside a string, go to the beginning of that
  899.     ;; string. this handles triple quoted, multi-line spanning
  900.     ;; strings.
  901.     (py-goto-initial-line)
  902.     (if (py-statement-opens-block-p)
  903.         (+ (current-indentation) py-indent-offset)
  904.       (current-indentation)))))))
  905.  
  906. (defun py-guess-indent-offset (&optional global)
  907.   "Guess a good value for, and change, `py-indent-offset'.
  908. By default (without a prefix arg), makes a buffer-local copy of
  909. `py-indent-offset' with the new value.  This will not affect any other
  910. Python buffers.  With a prefix arg, changes the global value of
  911. `py-indent-offset'.  This affects all Python buffers (that don't have
  912. their own buffer-local copy), both those currently existing and those
  913. created later in the Emacs session.
  914.  
  915. Some people use a different value for `py-indent-offset' than you use.
  916. There's no excuse for such foolishness, but sometimes you have to deal
  917. with their ugly code anyway.  This function examines the file and sets
  918. `py-indent-offset' to what it thinks it was when they created the
  919. mess.
  920.  
  921. Specifically, it searches forward from the statement containing point,
  922. looking for a line that opens a block of code.  `py-indent-offset' is
  923. set to the difference in indentation between that line and the Python
  924. statement following it.  If the search doesn't succeed going forward,
  925. it's tried again going backward."
  926.   (interactive "P")            ; raw prefix arg
  927.   (let (new-value
  928.     (start (point))
  929.     restart
  930.     (found nil)
  931.     colon-indent)
  932.     (py-goto-initial-line)
  933.     (while (not (or found (eobp)))
  934.       (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
  935.       (progn
  936.         (setq restart (point))
  937.         (py-goto-initial-line)
  938.         (if (py-statement-opens-block-p)
  939.         (setq found t)
  940.           (goto-char restart)))))
  941.     (if found
  942.     ()
  943.       (goto-char start)
  944.       (py-goto-initial-line)
  945.       (while (not (or found (bobp)))
  946.     (setq found
  947.           (and
  948.            (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
  949.            (or (py-goto-initial-line) t) ; always true -- side effect
  950.            (py-statement-opens-block-p)))))
  951.     (setq colon-indent (current-indentation)
  952.       found (and found (zerop (py-next-statement 1)))
  953.       new-value (- (current-indentation) colon-indent))
  954.     (goto-char start)
  955.     (if found
  956.     (progn
  957.       (funcall (if global 'kill-local-variable 'make-local-variable)
  958.            'py-indent-offset)
  959.       (setq py-indent-offset new-value)
  960.       (message "%s value of py-indent-offset set to %d"
  961.            (if global "Global" "Local")
  962.            py-indent-offset))
  963.       (error "Sorry, couldn't guess a value for py-indent-offset"))))
  964.  
  965. (defun py-shift-region (start end count)
  966.   (save-excursion
  967.     (goto-char end)   (beginning-of-line) (setq end (point))
  968.     (goto-char start) (beginning-of-line) (setq start (point))
  969.     (indent-rigidly start end count)))
  970.  
  971. (defun py-shift-region-left (start end &optional count)
  972.   "Shift region of Python code to the left.
  973. The lines from the line containing the start of the current region up
  974. to (but not including) the line containing the end of the region are
  975. shifted to the left, by `py-indent-offset' columns.
  976.  
  977. If a prefix argument is given, the region is instead shifted by that
  978. many columns."
  979.   (interactive "*r\nP")   ; region; raw prefix arg
  980.   (py-shift-region start end
  981.            (- (prefix-numeric-value
  982.                (or count py-indent-offset)))))
  983.  
  984. (defun py-shift-region-right (start end &optional count)
  985.   "Shift region of Python code to the right.
  986. The lines from the line containing the start of the current region up
  987. to (but not including) the line containing the end of the region are
  988. shifted to the right, by `py-indent-offset' columns.
  989.  
  990. If a prefix argument is given, the region is instead shifted by that
  991. many columns."
  992.   (interactive "*r\nP")   ; region; raw prefix arg
  993.   (py-shift-region start end (prefix-numeric-value
  994.                   (or count py-indent-offset))))
  995.  
  996. (defun py-indent-region (start end &optional indent-offset)
  997.   "Reindent a region of Python code.
  998. The lines from the line containing the start of the current region up
  999. to (but not including) the line containing the end of the region are
  1000. reindented.  If the first line of the region has a non-whitespace
  1001. character in the first column, the first line is left alone and the
  1002. rest of the region is reindented with respect to it.  Else the entire
  1003. region is reindented with respect to the (closest code or
  1004. indenting-comment) statement immediately preceding the region.
  1005.  
  1006. This is useful when code blocks are moved or yanked, when enclosing
  1007. control structures are introduced or removed, or to reformat code
  1008. using a new value for the indentation offset.
  1009.  
  1010. If a numeric prefix argument is given, it will be used as the value of
  1011. the indentation offset.  Else the value of `py-indent-offset' will be
  1012. used.
  1013.  
  1014. Warning: The region must be consistently indented before this function
  1015. is called!  This function does not compute proper indentation from
  1016. scratch (that's impossible in Python), it merely adjusts the existing
  1017. indentation to be correct in context.
  1018.  
  1019. Warning: This function really has no idea what to do with
  1020. non-indenting comment lines, and shifts them as if they were indenting
  1021. comment lines.  Fixing this appears to require telepathy.
  1022.  
  1023. Special cases: whitespace is deleted from blank lines; continuation
  1024. lines are shifted by the same amount their initial line was shifted,
  1025. in order to preserve their relative indentation with respect to their
  1026. initial line; and comment lines beginning in column 1 are ignored."
  1027.   (interactive "*r\nP")            ; region; raw prefix arg
  1028.   (save-excursion
  1029.     (goto-char end)   (beginning-of-line) (setq end (point-marker))
  1030.     (goto-char start) (beginning-of-line)
  1031.     (let ((py-indent-offset (prefix-numeric-value
  1032.                  (or indent-offset py-indent-offset)))
  1033.       (indents '(-1))        ; stack of active indent levels
  1034.       (target-column 0)        ; column to which to indent
  1035.       (base-shifted-by 0)        ; amount last base line was shifted
  1036.       (indent-base (if (looking-at "[ \t\n]")
  1037.                (py-compute-indentation)
  1038.              0))
  1039.       ci)
  1040.       (while (< (point) end)
  1041.     (setq ci (current-indentation))
  1042.     ;; figure out appropriate target column
  1043.     (cond
  1044.      ((or (eq (following-char) ?#)    ; comment in column 1
  1045.           (looking-at "[ \t]*$"))    ; entirely blank
  1046.       (setq target-column 0))
  1047.      ((py-continuation-line-p)    ; shift relative to base line
  1048.       (setq target-column (+ ci base-shifted-by)))
  1049.      (t                ; new base line
  1050.       (if (> ci (car indents))    ; going deeper; push it
  1051.           (setq indents (cons ci indents))
  1052.         ;; else we should have seen this indent before
  1053.         (setq indents (memq ci indents)) ; pop deeper indents
  1054.         (if (null indents)
  1055.         (error "Bad indentation in region, at line %d"
  1056.                (save-restriction
  1057.              (widen)
  1058.              (1+ (count-lines 1 (point)))))))
  1059.       (setq target-column (+ indent-base
  1060.                  (* py-indent-offset
  1061.                     (- (length indents) 2))))
  1062.       (setq base-shifted-by (- target-column ci))))
  1063.     ;; shift as needed
  1064.     (if (/= ci target-column)
  1065.         (progn
  1066.           (delete-horizontal-space)
  1067.           (indent-to target-column)))
  1068.     (forward-line 1))))
  1069.   (set-marker end nil))
  1070.  
  1071.  
  1072. ;; Functions for moving point
  1073. (defun py-previous-statement (count)
  1074.   "Go to the start of previous Python statement.
  1075. If the statement at point is the i'th Python statement, goes to the
  1076. start of statement i-COUNT.  If there is no such statement, goes to the
  1077. first statement.  Returns count of statements left to move.
  1078. `Statements' do not include blank, comment, or continuation lines."
  1079.   (interactive "p")            ; numeric prefix arg
  1080.   (if (< count 0) (py-next-statement (- count))
  1081.     (py-goto-initial-line)
  1082.     (let (start)
  1083.       (while (and
  1084.           (setq start (point))    ; always true -- side effect
  1085.           (> count 0)
  1086.           (zerop (forward-line -1))
  1087.           (py-goto-statement-at-or-above))
  1088.     (setq count (1- count)))
  1089.       (if (> count 0) (goto-char start)))
  1090.     count))
  1091.  
  1092. (defun py-next-statement (count)
  1093.   "Go to the start of next Python statement.
  1094. If the statement at point is the i'th Python statement, goes to the
  1095. start of statement i+COUNT.  If there is no such statement, goes to the
  1096. last statement.  Returns count of statements left to move.  `Statements'
  1097. do not include blank, comment, or continuation lines."
  1098.   (interactive "p")            ; numeric prefix arg
  1099.   (if (< count 0) (py-previous-statement (- count))
  1100.     (beginning-of-line)
  1101.     (let (start)
  1102.       (while (and
  1103.           (setq start (point))    ; always true -- side effect
  1104.           (> count 0)
  1105.           (py-goto-statement-below))
  1106.     (setq count (1- count)))
  1107.       (if (> count 0) (goto-char start)))
  1108.     count))
  1109.  
  1110. (defun py-goto-block-up (&optional nomark)
  1111.   "Move up to start of current block.
  1112. Go to the statement that starts the smallest enclosing block; roughly
  1113. speaking, this will be the closest preceding statement that ends with a
  1114. colon and is indented less than the statement you started on.  If
  1115. successful, also sets the mark to the starting point.
  1116.  
  1117. `\\[py-mark-block]' can be used afterward to mark the whole code
  1118. block, if desired.
  1119.  
  1120. If called from a program, the mark will not be set if optional argument
  1121. NOMARK is not nil."
  1122.   (interactive)
  1123.   (let ((start (point))
  1124.     (found nil)
  1125.     initial-indent)
  1126.     (py-goto-initial-line)
  1127.     ;; if on blank or non-indenting comment line, use the preceding stmt
  1128.     (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
  1129.     (progn
  1130.       (py-goto-statement-at-or-above)
  1131.       (setq found (py-statement-opens-block-p))))
  1132.     ;; search back for colon line indented less
  1133.     (setq initial-indent (current-indentation))
  1134.     (if (zerop initial-indent)
  1135.     ;; force fast exit
  1136.     (goto-char (point-min)))
  1137.     (while (not (or found (bobp)))
  1138.       (setq found
  1139.         (and
  1140.          (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
  1141.          (or (py-goto-initial-line) t) ; always true -- side effect
  1142.          (< (current-indentation) initial-indent)
  1143.          (py-statement-opens-block-p))))
  1144.     (if found
  1145.     (progn
  1146.       (or nomark (push-mark start))
  1147.       (back-to-indentation))
  1148.       (goto-char start)
  1149.       (error "Enclosing block not found"))))
  1150.  
  1151. (defun beginning-of-python-def-or-class (&optional class)
  1152.   "Move point to start of def (or class, with prefix arg).
  1153.  
  1154. Searches back for the closest preceding `def'.  If you supply a prefix
  1155. arg, looks for a `class' instead.  The docs assume the `def' case;
  1156. just substitute `class' for `def' for the other case.
  1157.  
  1158. If point is in a def statement already, and after the `d', simply
  1159. moves point to the start of the statement.
  1160.  
  1161. Else (point is not in a def statement, or at or before the `d' of a
  1162. def statement), searches for the closest preceding def statement, and
  1163. leaves point at its start.  If no such statement can be found, leaves
  1164. point at the start of the buffer.
  1165.  
  1166. Returns t iff a def statement is found by these rules.
  1167.  
  1168. Note that doing this command repeatedly will take you closer to the
  1169. start of the buffer each time.
  1170.  
  1171. If you want to mark the current def/class, see
  1172. `\\[mark-python-def-or-class]'."
  1173.   (interactive "P")            ; raw prefix arg
  1174.   (let ((at-or-before-p (<= (current-column) (current-indentation)))
  1175.     (start-of-line (progn (beginning-of-line) (point)))
  1176.     (start-of-stmt (progn (py-goto-initial-line) (point))))
  1177.     (if (or (/= start-of-stmt start-of-line)
  1178.         (not at-or-before-p))
  1179.     (end-of-line))            ; OK to match on this line
  1180.     (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
  1181.             nil 'move)))
  1182.  
  1183. (defun end-of-python-def-or-class (&optional class)
  1184.   "Move point beyond end of def (or class, with prefix arg) body.
  1185.  
  1186. By default, looks for an appropriate `def'.  If you supply a prefix arg,
  1187. looks for a `class' instead.  The docs assume the `def' case; just
  1188. substitute `class' for `def' for the other case.
  1189.  
  1190. If point is in a def statement already, this is the def we use.
  1191.  
  1192. Else if the def found by `\\[beginning-of-python-def-or-class]'
  1193. contains the statement you started on, that's the def we use.
  1194.  
  1195. Else we search forward for the closest following def, and use that.
  1196.  
  1197. If a def can be found by these rules, point is moved to the start of
  1198. the line immediately following the def block, and the position of the
  1199. start of the def is returned.
  1200.  
  1201. Else point is moved to the end of the buffer, and nil is returned.
  1202.  
  1203. Note that doing this command repeatedly will take you closer to the
  1204. end of the buffer each time.
  1205.  
  1206. If you want to mark the current def/class, see
  1207. `\\[mark-python-def-or-class]'."
  1208.   (interactive "P")            ; raw prefix arg
  1209.   (let ((start (progn (py-goto-initial-line) (point)))
  1210.     (which (if class "class" "def"))
  1211.     (state 'not-found))
  1212.     ;; move point to start of appropriate def/class
  1213.     (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
  1214.     (setq state 'at-beginning)
  1215.       ;; else see if beginning-of-python-def-or-class hits container
  1216.       (if (and (beginning-of-python-def-or-class class)
  1217.            (progn (py-goto-beyond-block)
  1218.               (> (point) start)))
  1219.       (setq state 'at-end)
  1220.     ;; else search forward
  1221.     (goto-char start)
  1222.     (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
  1223.         (progn (setq state 'at-beginning)
  1224.            (beginning-of-line)))))
  1225.     (cond
  1226.      ((eq state 'at-beginning) (py-goto-beyond-block) t)
  1227.      ((eq state 'at-end) t)
  1228.      ((eq state 'not-found) nil)
  1229.      (t (error "internal error in end-of-python-def-or-class")))))
  1230.  
  1231.  
  1232. ;; Functions for marking regions
  1233. (defun py-mark-block (&optional extend just-move)
  1234.   "Mark following block of lines.  With prefix arg, mark structure.
  1235. Easier to use than explain.  It sets the region to an `interesting'
  1236. block of succeeding lines.  If point is on a blank line, it goes down to
  1237. the next non-blank line.  That will be the start of the region.  The end
  1238. of the region depends on the kind of line at the start:
  1239.  
  1240.  - If a comment, the region will include all succeeding comment lines up
  1241.    to (but not including) the next non-comment line (if any).
  1242.  
  1243.  - Else if a prefix arg is given, and the line begins one of these
  1244.    structures:
  1245.  
  1246.      if elif else try except finally for while def class
  1247.  
  1248.    the region will be set to the body of the structure, including
  1249.    following blocks that `belong' to it, but excluding trailing blank
  1250.    and comment lines.  E.g., if on a `try' statement, the `try' block
  1251.    and all (if any) of the following `except' and `finally' blocks
  1252.    that belong to the `try' structure will be in the region.  Ditto
  1253.    for if/elif/else, for/else and while/else structures, and (a bit
  1254.    degenerate, since they're always one-block structures) def and
  1255.    class blocks.
  1256.  
  1257.  - Else if no prefix argument is given, and the line begins a Python
  1258.    block (see list above), and the block is not a `one-liner' (i.e.,
  1259.    the statement ends with a colon, not with code), the region will
  1260.    include all succeeding lines up to (but not including) the next
  1261.    code statement (if any) that's indented no more than the starting
  1262.    line, except that trailing blank and comment lines are excluded.
  1263.    E.g., if the starting line begins a multi-statement `def'
  1264.    structure, the region will be set to the full function definition,
  1265.    but without any trailing `noise' lines.
  1266.  
  1267.  - Else the region will include all succeeding lines up to (but not
  1268.    including) the next blank line, or code or indenting-comment line
  1269.    indented strictly less than the starting line.  Trailing indenting
  1270.    comment lines are included in this case, but not trailing blank
  1271.    lines.
  1272.  
  1273. A msg identifying the location of the mark is displayed in the echo
  1274. area; or do `\\[exchange-point-and-mark]' to flip down to the end.
  1275.  
  1276. If called from a program, optional argument EXTEND plays the role of
  1277. the prefix arg, and if optional argument JUST-MOVE is not nil, just
  1278. moves to the end of the block (& does not set mark or display a msg)."
  1279.   (interactive "P")            ; raw prefix arg
  1280.   (py-goto-initial-line)
  1281.   ;; skip over blank lines
  1282.   (while (and
  1283.       (looking-at "[ \t]*$")    ; while blank line
  1284.       (not (eobp)))            ; & somewhere to go
  1285.     (forward-line 1))
  1286.   (if (eobp)
  1287.       (error "Hit end of buffer without finding a non-blank stmt"))
  1288.   (let ((initial-pos (point))
  1289.     (initial-indent (current-indentation))
  1290.     last-pos            ; position of last stmt in region
  1291.     (followers
  1292.      '((if elif else) (elif elif else) (else)
  1293.        (try except finally) (except except) (finally)
  1294.        (for else) (while else)
  1295.        (def) (class) ) )
  1296.     first-symbol next-symbol)
  1297.  
  1298.     (cond
  1299.      ;; if comment line, suck up the following comment lines
  1300.      ((looking-at "[ \t]*#")
  1301.       (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
  1302.       (re-search-backward "^[ \t]*#")    ; and back to last comment in block
  1303.       (setq last-pos (point)))
  1304.  
  1305.      ;; else if line is a block line and EXTEND given, suck up
  1306.      ;; the whole structure
  1307.      ((and extend
  1308.        (setq first-symbol (py-suck-up-first-keyword) )
  1309.        (assq first-symbol followers))
  1310.       (while (and
  1311.           (or (py-goto-beyond-block) t) ; side effect
  1312.           (forward-line -1)        ; side effect
  1313.           (setq last-pos (point))    ; side effect
  1314.           (py-goto-statement-below)
  1315.           (= (current-indentation) initial-indent)
  1316.           (setq next-symbol (py-suck-up-first-keyword))
  1317.           (memq next-symbol (cdr (assq first-symbol followers))))
  1318.     (setq first-symbol next-symbol)))
  1319.  
  1320.      ;; else if line *opens* a block, search for next stmt indented <=
  1321.      ((py-statement-opens-block-p)
  1322.       (while (and
  1323.           (setq last-pos (point))    ; always true -- side effect
  1324.           (py-goto-statement-below)
  1325.           (> (current-indentation) initial-indent))
  1326.     nil))
  1327.  
  1328.      ;; else plain code line; stop at next blank line, or stmt or
  1329.      ;; indenting comment line indented <
  1330.      (t
  1331.       (while (and
  1332.           (setq last-pos (point))    ; always true -- side effect
  1333.           (or (py-goto-beyond-final-line) t)
  1334.           (not (looking-at "[ \t]*$")) ; stop at blank line
  1335.           (or
  1336.            (>= (current-indentation) initial-indent)
  1337.            (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
  1338.     nil)))
  1339.  
  1340.     ;; skip to end of last stmt
  1341.     (goto-char last-pos)
  1342.     (py-goto-beyond-final-line)
  1343.  
  1344.     ;; set mark & display
  1345.     (if just-move
  1346.     ()                ; just return
  1347.       (push-mark (point) 'no-msg)
  1348.       (forward-line -1)
  1349.       (message "Mark set after: %s" (py-suck-up-leading-text))
  1350.       (goto-char initial-pos))))
  1351.  
  1352. (defun mark-python-def-or-class (&optional class)
  1353.   "Set region to body of def (or class, with prefix arg) enclosing point.
  1354. Pushes the current mark, then point, on the mark ring (all language
  1355. modes do this, but although it's handy it's never documented ...).
  1356.  
  1357. In most Emacs language modes, this function bears at least a
  1358. hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
  1359. `\\[beginning-of-python-def-or-class]'.
  1360.  
  1361. And in earlier versions of Python mode, all 3 were tightly connected.
  1362. Turned out that was more confusing than useful: the `goto start' and
  1363. `goto end' commands are usually used to search through a file, and
  1364. people expect them to act a lot like `search backward' and `search
  1365. forward' string-search commands.  But because Python `def' and `class'
  1366. can nest to arbitrary levels, finding the smallest def containing
  1367. point cannot be done via a simple backward search: the def containing
  1368. point may not be the closest preceding def, or even the closest
  1369. preceding def that's indented less.  The fancy algorithm required is
  1370. appropriate for the usual uses of this `mark' command, but not for the
  1371. `goto' variations.
  1372.  
  1373. So the def marked by this command may not be the one either of the
  1374. `goto' commands find: If point is on a blank or non-indenting comment
  1375. line, moves back to start of the closest preceding code statement or
  1376. indenting comment line.  If this is a `def' statement, that's the def
  1377. we use.  Else searches for the smallest enclosing `def' block and uses
  1378. that.  Else signals an error.
  1379.  
  1380. When an enclosing def is found: The mark is left immediately beyond
  1381. the last line of the def block.  Point is left at the start of the
  1382. def, except that: if the def is preceded by a number of comment lines
  1383. followed by (at most) one optional blank line, point is left at the
  1384. start of the comments; else if the def is preceded by a blank line,
  1385. point is left at its start.
  1386.  
  1387. The intent is to mark the containing def/class and its associated
  1388. documentation, to make moving and duplicating functions and classes
  1389. pleasant."
  1390.   (interactive "P")            ; raw prefix arg
  1391.   (let ((start (point))
  1392.     (which (if class "class" "def")))
  1393.     (push-mark start)
  1394.     (if (not (py-go-up-tree-to-keyword which))
  1395.     (progn (goto-char start)
  1396.            (error "Enclosing %s not found" which))
  1397.       ;; else enclosing def/class found
  1398.       (setq start (point))
  1399.       (py-goto-beyond-block)
  1400.       (push-mark (point))
  1401.       (goto-char start)
  1402.       (if (zerop (forward-line -1))    ; if there is a preceding line
  1403.       (progn
  1404.         (if (looking-at "[ \t]*$")    ; it's blank
  1405.         (setq start (point))    ; so reset start point
  1406.           (goto-char start))    ; else try again
  1407.         (if (zerop (forward-line -1))
  1408.         (if (looking-at "[ \t]*#") ; a comment
  1409.             ;; look back for non-comment line
  1410.             ;; tricky: note that the regexp matches a blank
  1411.             ;; line, cuz \n is in the 2nd character class
  1412.             (and
  1413.              (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
  1414.              (forward-line 1))
  1415.           ;; no comment, so go back
  1416.           (goto-char start))))))))
  1417.  
  1418. (defun py-comment-region (start end &optional uncomment-p)
  1419.   "Comment out region of code; with prefix arg, uncomment region.
  1420. The lines from the line containing the start of the current region up
  1421. to (but not including) the line containing the end of the region are
  1422. commented out, by inserting the string `py-block-comment-prefix' at
  1423. the start of each line.  With a prefix arg, removes
  1424. `py-block-comment-prefix' from the start of each line instead."
  1425.   (interactive "*r\nP")   ; region; raw prefix arg
  1426.   (goto-char end)   (beginning-of-line) (setq end (point))
  1427.   (goto-char start) (beginning-of-line) (setq start (point))
  1428.   (let ((prefix-len (length py-block-comment-prefix)) )
  1429.     (save-excursion
  1430.       (save-restriction
  1431.     (narrow-to-region start end)
  1432.     (while (not (eobp))
  1433.       (if uncomment-p
  1434.           (and (string= py-block-comment-prefix
  1435.                 (buffer-substring
  1436.                  (point) (+ (point) prefix-len)))
  1437.            (delete-char prefix-len))
  1438.         (insert py-block-comment-prefix))
  1439.       (forward-line 1))))))
  1440.  
  1441.  
  1442. ;; Documentation functions
  1443.  
  1444. ;; dump the long form of the mode blurb; does the usual doc escapes,
  1445. ;; plus lines of the form ^[vc]:name$ to suck variable & command docs
  1446. ;; out of the right places, along with the keys they're on & current
  1447. ;; values
  1448. (defun py-dump-help-string (str)
  1449.   (with-output-to-temp-buffer "*Help*"
  1450.     (let ((locals (buffer-local-variables))
  1451.       funckind funcname func funcdoc
  1452.       (start 0) mstart end
  1453.       keys )
  1454.       (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
  1455.     (setq mstart (match-beginning 0)  end (match-end 0)
  1456.           funckind (substring str (match-beginning 1) (match-end 1))
  1457.           funcname (substring str (match-beginning 2) (match-end 2))
  1458.           func (intern funcname))
  1459.     (princ (substitute-command-keys (substring str start mstart)))
  1460.     (cond
  1461.      ((equal funckind "c")        ; command
  1462.       (setq funcdoc (documentation func)
  1463.         keys (concat
  1464.               "Key(s): "
  1465.               (mapconcat 'key-description
  1466.                  (where-is-internal func py-mode-map)
  1467.                  ", "))))
  1468.      ((equal funckind "v")        ; variable
  1469.       (setq funcdoc (substitute-command-keys
  1470.              (get func 'variable-documentation))
  1471.         keys (if (assq func locals)
  1472.              (concat
  1473.               "Local/Global values: "
  1474.               (prin1-to-string (symbol-value func))
  1475.               " / "
  1476.               (prin1-to-string (default-value func)))
  1477.                (concat
  1478.             "Value: "
  1479.             (prin1-to-string (symbol-value func))))))
  1480.      (t                ; unexpected
  1481.       (error "Error in py-dump-help-string, tag `%s'" funckind)))
  1482.     (princ (format "\n-> %s:\t%s\t%s\n\n"
  1483.                (if (equal funckind "c") "Command" "Variable")
  1484.                funcname keys))
  1485.     (princ funcdoc)
  1486.     (terpri)
  1487.     (setq start end))
  1488.       (princ (substitute-command-keys (substring str start))))
  1489.     (print-help-return-message)))
  1490.  
  1491. (defun py-describe-mode ()
  1492.   "Dump long form of Python-mode docs."
  1493.   (interactive)
  1494.   (py-dump-help-string "Major mode for editing Python files.
  1495. Knows about Python indentation, tokens, comments and continuation lines.
  1496. Paragraphs are separated by blank lines only.
  1497.  
  1498. Major sections below begin with the string `@'; specific function and
  1499. variable docs begin with `->'.
  1500.  
  1501. @EXECUTING PYTHON CODE
  1502.  
  1503. \\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
  1504. \\[py-execute-region]\tsends the current region
  1505. \\[py-shell]\tstarts a Python interpreter window; this will be used by
  1506. \tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
  1507. %c:py-execute-buffer
  1508. %c:py-execute-region
  1509. %c:py-shell
  1510.  
  1511. @VARIABLES
  1512.  
  1513. py-indent-offset\tindentation increment
  1514. py-block-comment-prefix\tcomment string used by py-comment-region
  1515.  
  1516. py-python-command\tshell command to invoke Python interpreter
  1517. py-scroll-process-buffer\talways scroll Python process buffer
  1518. py-temp-directory\tdirectory used for temp files (if needed)
  1519.  
  1520. py-beep-if-tab-change\tring the bell if tab-width is changed
  1521. %v:py-indent-offset
  1522. %v:py-block-comment-prefix
  1523. %v:py-python-command
  1524. %v:py-scroll-process-buffer
  1525. %v:py-temp-directory
  1526. %v:py-beep-if-tab-change
  1527.  
  1528. @KINDS OF LINES
  1529.  
  1530. Each physical line in the file is either a `continuation line' (the
  1531. preceding line ends with a backslash that's not part of a comment, or
  1532. the paren/bracket/brace nesting level at the start of the line is
  1533. non-zero, or both) or an `initial line' (everything else).
  1534.  
  1535. An initial line is in turn a `blank line' (contains nothing except
  1536. possibly blanks or tabs), a `comment line' (leftmost non-blank
  1537. character is `#'), or a `code line' (everything else).
  1538.  
  1539. Comment Lines
  1540.  
  1541. Although all comment lines are treated alike by Python, Python mode
  1542. recognizes two kinds that act differently with respect to indentation.
  1543.  
  1544. An `indenting comment line' is a comment line with a blank, tab or
  1545. nothing after the initial `#'.  The indentation commands (see below)
  1546. treat these exactly as if they were code lines: a line following an
  1547. indenting comment line will be indented like the comment line.  All
  1548. other comment lines (those with a non-whitespace character immediately
  1549. following the initial `#') are `non-indenting comment lines', and
  1550. their indentation is ignored by the indentation commands.
  1551.  
  1552. Indenting comment lines are by far the usual case, and should be used
  1553. whenever possible.  Non-indenting comment lines are useful in cases
  1554. like these:
  1555.  
  1556. \ta = b   # a very wordy single-line comment that ends up being
  1557. \t        #... continued onto another line
  1558.  
  1559. \tif a == b:
  1560. ##\t\tprint 'panic!' # old code we've `commented out'
  1561. \t\treturn a
  1562.  
  1563. Since the `#...' and `##' comment lines have a non-whitespace
  1564. character following the initial `#', Python mode ignores them when
  1565. computing the proper indentation for the next line.
  1566.  
  1567. Continuation Lines and Statements
  1568.  
  1569. The Python-mode commands generally work on statements instead of on
  1570. individual lines, where a `statement' is a comment or blank line, or a
  1571. code line and all of its following continuation lines (if any)
  1572. considered as a single logical unit.  The commands in this mode
  1573. generally (when it makes sense) automatically move to the start of the
  1574. statement containing point, even if point happens to be in the middle
  1575. of some continuation line.
  1576.  
  1577.  
  1578. @INDENTATION
  1579.  
  1580. Primarily for entering new code:
  1581. \t\\[indent-for-tab-command]\t indent line appropriately
  1582. \t\\[py-newline-and-indent]\t insert newline, then indent
  1583. \t\\[py-delete-char]\t reduce indentation, or delete single character
  1584.  
  1585. Primarily for reindenting existing code:
  1586. \t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
  1587. \t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
  1588.  
  1589. \t\\[py-indent-region]\t reindent region to match its context
  1590. \t\\[py-shift-region-left]\t shift region left by py-indent-offset
  1591. \t\\[py-shift-region-right]\t shift region right by py-indent-offset
  1592.  
  1593. Unlike most programming languages, Python uses indentation, and only
  1594. indentation, to specify block structure.  Hence the indentation supplied
  1595. automatically by Python-mode is just an educated guess:  only you know
  1596. the block structure you intend, so only you can supply correct
  1597. indentation.
  1598.  
  1599. The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
  1600. the indentation of preceding statements.  E.g., assuming
  1601. py-indent-offset is 4, after you enter
  1602. \tif a > 0: \\[py-newline-and-indent]
  1603. the cursor will be moved to the position of the `_' (_ is not a
  1604. character in the file, it's just used here to indicate the location of
  1605. the cursor):
  1606. \tif a > 0:
  1607. \t    _
  1608. If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
  1609. to
  1610. \tif a > 0:
  1611. \t    c = d
  1612. \t    _
  1613. Python-mode cannot know whether that's what you intended, or whether
  1614. \tif a > 0:
  1615. \t    c = d
  1616. \t_
  1617. was your intent.  In general, Python-mode either reproduces the
  1618. indentation of the (closest code or indenting-comment) preceding
  1619. statement, or adds an extra py-indent-offset blanks if the preceding
  1620. statement has `:' as its last significant (non-whitespace and non-
  1621. comment) character.  If the suggested indentation is too much, use
  1622. \\[py-delete-char] to reduce it.
  1623.  
  1624. Continuation lines are given extra indentation.  If you don't like the
  1625. suggested indentation, change it to something you do like, and Python-
  1626. mode will strive to indent later lines of the statement in the same way.
  1627.  
  1628. If a line is a continuation line by virtue of being in an unclosed
  1629. paren/bracket/brace structure (`list', for short), the suggested
  1630. indentation depends on whether the current line contains the first item
  1631. in the list.  If it does, it's indented py-indent-offset columns beyond
  1632. the indentation of the line containing the open bracket.  If you don't
  1633. like that, change it by hand.  The remaining items in the list will mimic
  1634. whatever indentation you give to the first item.
  1635.  
  1636. If a line is a continuation line because the line preceding it ends with
  1637. a backslash, the third and following lines of the statement inherit their
  1638. indentation from the line preceding them.  The indentation of the second
  1639. line in the statement depends on the form of the first (base) line:  if
  1640. the base line is an assignment statement with anything more interesting
  1641. than the backslash following the leftmost assigning `=', the second line
  1642. is indented two columns beyond that `='.  Else it's indented to two
  1643. columns beyond the leftmost solid chunk of non-whitespace characters on
  1644. the base line.
  1645.  
  1646. Warning:  indent-region should not normally be used!  It calls \\[indent-for-tab-command]
  1647. repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
  1648. structure you intend.
  1649. %c:indent-for-tab-command
  1650. %c:py-newline-and-indent
  1651. %c:py-delete-char
  1652.  
  1653.  
  1654. The next function may be handy when editing code you didn't write:
  1655. %c:py-guess-indent-offset
  1656.  
  1657.  
  1658. The remaining `indent' functions apply to a region of Python code.  They
  1659. assume the block structure (equals indentation, in Python) of the region
  1660. is correct, and alter the indentation in various ways while preserving
  1661. the block structure:
  1662. %c:py-indent-region
  1663. %c:py-shift-region-left
  1664. %c:py-shift-region-right
  1665.  
  1666. @MARKING & MANIPULATING REGIONS OF CODE
  1667.  
  1668. \\[py-mark-block]\t mark block of lines
  1669. \\[mark-python-def-or-class]\t mark smallest enclosing def
  1670. \\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
  1671. \\[py-comment-region]\t comment out region of code
  1672. \\[universal-argument] \\[py-comment-region]\t uncomment region of code
  1673. %c:py-mark-block
  1674. %c:mark-python-def-or-class
  1675. %c:py-comment-region
  1676.  
  1677. @MOVING POINT
  1678.  
  1679. \\[py-previous-statement]\t move to statement preceding point
  1680. \\[py-next-statement]\t move to statement following point
  1681. \\[py-goto-block-up]\t move up to start of current block
  1682. \\[beginning-of-python-def-or-class]\t move to start of def
  1683. \\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
  1684. \\[end-of-python-def-or-class]\t move to end of def
  1685. \\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
  1686.  
  1687. The first two move to one statement beyond the statement that contains
  1688. point.  A numeric prefix argument tells them to move that many
  1689. statements instead.  Blank lines, comment lines, and continuation lines
  1690. do not count as `statements' for these commands.  So, e.g., you can go
  1691. to the first code statement in a file by entering
  1692. \t\\[beginning-of-buffer]\t to move to the top of the file
  1693. \t\\[py-next-statement]\t to skip over initial comments and blank lines
  1694. Or do `\\[py-previous-statement]' with a huge prefix argument.
  1695. %c:py-previous-statement
  1696. %c:py-next-statement
  1697. %c:py-goto-block-up
  1698. %c:beginning-of-python-def-or-class
  1699. %c:end-of-python-def-or-class
  1700.  
  1701. @LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
  1702.  
  1703. `\\[indent-new-comment-line]' is handy for entering a multi-line comment.
  1704.  
  1705. `\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
  1706. overall class and def structure of a module.
  1707.  
  1708. `\\[back-to-indentation]' moves point to a line's first non-blank character.
  1709.  
  1710. `\\[indent-relative]' is handy for creating odd indentation.
  1711.  
  1712. @OTHER EMACS HINTS
  1713.  
  1714. If you don't like the default value of a variable, change its value to
  1715. whatever you do like by putting a `setq' line in your .emacs file.
  1716. E.g., to set the indentation increment to 4, put this line in your
  1717. .emacs:
  1718. \t(setq  py-indent-offset  4)
  1719. To see the value of a variable, do `\\[describe-variable]' and enter the variable
  1720. name at the prompt.
  1721.  
  1722. When entering a key sequence like `C-c C-n', it is not necessary to
  1723. release the CONTROL key after doing the `C-c' part -- it suffices to
  1724. press the CONTROL key, press and release `c' (while still holding down
  1725. CONTROL), press and release `n' (while still holding down CONTROL), &
  1726. then release CONTROL.
  1727.  
  1728. Entering Python mode calls with no arguments the value of the variable
  1729. `python-mode-hook', if that value exists and is not nil; for backward
  1730. compatibility it also tries `py-mode-hook'; see the `Hooks' section of
  1731. the Elisp manual for details.
  1732.  
  1733. Obscure:  When python-mode is first loaded, it looks for all bindings
  1734. to newline-and-indent in the global keymap, and shadows them with
  1735. local bindings to py-newline-and-indent."))
  1736.  
  1737.  
  1738. ;; Helper functions
  1739. (defvar py-parse-state-re
  1740.   (concat
  1741.    "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
  1742.    "\\|"
  1743.    "^[^ #\t\n]"))
  1744.  
  1745. ;; returns the parse state at point (see parse-partial-sexp docs)
  1746. (defun py-parse-state ()
  1747.   (save-excursion
  1748.     (let ((here (point)) )
  1749.       ;; back up to the first preceding line (if any; else start of
  1750.       ;; buffer) that begins with a popular Python keyword, or a non-
  1751.       ;; whitespace and non-comment character.  These are good places
  1752.       ;; to start parsing to see whether where we started is at a
  1753.       ;; non-zero nesting level.  It may be slow for people who write
  1754.       ;; huge code blocks or huge lists ... tough beans.
  1755.       (re-search-backward py-parse-state-re nil 'move)
  1756.       (beginning-of-line)
  1757.       (parse-partial-sexp (point) here))))
  1758.  
  1759. ;; if point is at a non-zero nesting level, returns the number of the
  1760. ;; character that opens the smallest enclosing unclosed list; else
  1761. ;; returns nil.
  1762. (defun py-nesting-level ()
  1763.   (let ((status (py-parse-state)) )
  1764.     (if (zerop (car status))
  1765.     nil                ; not in a nest
  1766.       (car (cdr status)))))        ; char# of open bracket
  1767.  
  1768. ;; t iff preceding line ends with backslash that's not in a comment
  1769. (defun py-backslash-continuation-line-p ()
  1770.   (save-excursion
  1771.     (beginning-of-line)
  1772.     (and
  1773.      ;; use a cheap test first to avoid the regexp if possible
  1774.      ;; use 'eq' because char-after may return nil
  1775.      (eq (char-after (- (point) 2)) ?\\ )
  1776.      ;; make sure; since eq test passed, there is a preceding line
  1777.      (forward-line -1)            ; always true -- side effect
  1778.      (looking-at py-continued-re))))
  1779.  
  1780. ;; t iff current line is a continuation line
  1781. (defun py-continuation-line-p ()
  1782.   (save-excursion
  1783.     (beginning-of-line)
  1784.     (or (py-backslash-continuation-line-p)
  1785.     (py-nesting-level))))
  1786.  
  1787. ;; go to initial line of current statement; usually this is the line
  1788. ;; we're on, but if we're on the 2nd or following lines of a
  1789. ;; continuation block, we need to go up to the first line of the
  1790. ;; block.
  1791. ;;
  1792. ;; Tricky: We want to avoid quadratic-time behavior for long continued
  1793. ;; blocks, whether of the backslash or open-bracket varieties, or a
  1794. ;; mix of the two.  The following manages to do that in the usual
  1795. ;; cases.
  1796. (defun py-goto-initial-line ()
  1797.   (let ( open-bracket-pos )
  1798.     (while (py-continuation-line-p)
  1799.       (beginning-of-line)
  1800.       (if (py-backslash-continuation-line-p)
  1801.       (while (py-backslash-continuation-line-p)
  1802.         (forward-line -1))
  1803.     ;; else zip out of nested brackets/braces/parens
  1804.     (while (setq open-bracket-pos (py-nesting-level))
  1805.       (goto-char open-bracket-pos)))))
  1806.   (beginning-of-line))
  1807.  
  1808. ;; go to point right beyond final line of current statement; usually
  1809. ;; this is the start of the next line, but if this is a multi-line
  1810. ;; statement we need to skip over the continuation lines.  Tricky:
  1811. ;; Again we need to be clever to avoid quadratic time behavior.
  1812. (defun py-goto-beyond-final-line ()
  1813.   (forward-line 1)
  1814.   (let (state)
  1815.     (while (and (py-continuation-line-p)
  1816.         (not (eobp)))
  1817.       ;; skip over the backslash flavor
  1818.       (while (and (py-backslash-continuation-line-p)
  1819.           (not (eobp)))
  1820.     (forward-line 1))
  1821.       ;; if in nest, zip to the end of the nest
  1822.       (setq state (py-parse-state))
  1823.       (if (and (not (zerop (car state)))
  1824.            (not (eobp)))
  1825.       (progn
  1826.         ;; BUG ALERT: I could swear, from reading the docs, that
  1827.         ;; the 3rd argument should be plain 0
  1828.         (parse-partial-sexp (point) (point-max) (- 0 (car state))
  1829.                 nil state)
  1830.         (forward-line 1))))))
  1831.  
  1832. ;; t iff statement opens a block == iff it ends with a colon that's
  1833. ;; not in a comment.  point should be at the start of a statement
  1834. (defun py-statement-opens-block-p ()
  1835.   (save-excursion
  1836.     (let ((start (point))
  1837.       (finish (progn (py-goto-beyond-final-line) (1- (point))))
  1838.       (searching t)
  1839.       (answer nil)
  1840.       state)
  1841.       (goto-char start)
  1842.       (while searching
  1843.     ;; look for a colon with nothing after it except whitespace, and
  1844.     ;; maybe a comment
  1845.     (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
  1846.                    finish t)
  1847.         (if (eq (point) finish)    ; note: no `else' clause; just
  1848.                     ; keep searching if we're not at
  1849.                     ; the end yet
  1850.         ;; sure looks like it opens a block -- but it might
  1851.         ;; be in a comment
  1852.         (progn
  1853.           (setq searching nil)    ; search is done either way
  1854.           (setq state (parse-partial-sexp start
  1855.                           (match-beginning 0)))
  1856.           (setq answer (not (nth 4 state)))))
  1857.       ;; search failed: couldn't find another interesting colon
  1858.       (setq searching nil)))
  1859.       answer)))
  1860.  
  1861. ;; go to point right beyond final line of block begun by the current
  1862. ;; line.  This is the same as where py-goto-beyond-final-line goes
  1863. ;; unless we're on colon line, in which case we go to the end of the
  1864. ;; block.  assumes point is at bolp
  1865. (defun py-goto-beyond-block ()
  1866.   (if (py-statement-opens-block-p)
  1867.       (py-mark-block nil 'just-move)
  1868.     (py-goto-beyond-final-line)))
  1869.  
  1870. ;; go to start of first statement (not blank or comment or
  1871. ;; continuation line) at or preceding point.  returns t if there is
  1872. ;; one, else nil
  1873. (defun py-goto-statement-at-or-above ()
  1874.   (py-goto-initial-line)
  1875.   (if (looking-at py-blank-or-comment-re)
  1876.       ;; skip back over blank & comment lines
  1877.       ;; note:  will skip a blank or comment line that happens to be
  1878.       ;; a continuation line too
  1879.       (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
  1880.       (progn (py-goto-initial-line) t)
  1881.     nil)
  1882.     t))
  1883.  
  1884. ;; go to start of first statement (not blank or comment or
  1885. ;; continuation line) following the statement containing point returns
  1886. ;; t if there is one, else nil
  1887. (defun py-goto-statement-below ()
  1888.   (beginning-of-line)
  1889.   (let ((start (point)))
  1890.     (py-goto-beyond-final-line)
  1891.     (while (and
  1892.         (looking-at py-blank-or-comment-re)
  1893.         (not (eobp)))
  1894.       (forward-line 1))
  1895.     (if (eobp)
  1896.     (progn (goto-char start) nil)
  1897.       t)))
  1898.  
  1899. ;; go to start of statement, at or preceding point, starting with
  1900. ;; keyword KEY.  Skips blank lines and non-indenting comments upward
  1901. ;; first.  If that statement starts with KEY, done, else go back to
  1902. ;; first enclosing block starting with KEY.  If successful, leaves
  1903. ;; point at the start of the KEY line & returns t.  Else leaves point
  1904. ;; at an undefined place & returns nil.
  1905. (defun py-go-up-tree-to-keyword (key)
  1906.   ;; skip blanks and non-indenting #
  1907.   (py-goto-initial-line)
  1908.   (while (and
  1909.       (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
  1910.       (zerop (forward-line -1)))    ; go back
  1911.     nil)
  1912.   (py-goto-initial-line)
  1913.   (let* ((re (concat "[ \t]*" key "\\b"))
  1914.      (case-fold-search nil)        ; let* so looking-at sees this
  1915.      (found (looking-at re))
  1916.      (dead nil))
  1917.     (while (not (or found dead))
  1918.       (condition-case nil        ; in case no enclosing block
  1919.       (py-goto-block-up 'no-mark)
  1920.     (error (setq dead t)))
  1921.       (or dead (setq found (looking-at re))))
  1922.     (beginning-of-line)
  1923.     found))
  1924.  
  1925. ;; return string in buffer from start of indentation to end of line;
  1926. ;; prefix "..." if leading whitespace was skipped
  1927. (defun py-suck-up-leading-text ()
  1928.   (save-excursion
  1929.     (back-to-indentation)
  1930.     (concat
  1931.      (if (bolp) "" "...")
  1932.      (buffer-substring (point) (progn (end-of-line) (point))))))
  1933.  
  1934. ;; assuming point at bolp, return first keyword ([a-z]+) on the line,
  1935. ;; as a Lisp symbol; return nil if none
  1936. (defun py-suck-up-first-keyword ()
  1937.   (let ((case-fold-search nil))
  1938.     (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
  1939.     (intern (buffer-substring (match-beginning 1) (match-end 1)))
  1940.       nil)))
  1941.  
  1942. (defun py-make-temp-name ()
  1943.   (make-temp-name
  1944.    (concat (file-name-as-directory py-temp-directory) "python")))
  1945.  
  1946. (defun py-delete-file-silently (fname)
  1947.   (condition-case nil
  1948.       (delete-file fname)
  1949.     (error nil)))
  1950.  
  1951. (defun py-kill-emacs-hook ()
  1952.   ;; delete our temp files
  1953.   (while py-file-queue
  1954.     (py-delete-file-silently (car py-file-queue))
  1955.     (setq py-file-queue (cdr py-file-queue)))
  1956.   (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
  1957.       ;; run the hook we inherited, if any
  1958.       (and py-inherited-kill-emacs-hook
  1959.        (funcall py-inherited-kill-emacs-hook))))
  1960.  
  1961. ;; make PROCESS's buffer visible, append STRING to it, and force
  1962. ;; display; also make shell-mode believe the user typed this string,
  1963. ;; so that kill-output-from-shell and show-output-from-shell work
  1964. ;; "right"
  1965. (defun py-append-to-process-buffer (process string)
  1966.   (let ((cbuf (current-buffer))
  1967.     (pbuf (process-buffer process))
  1968.     (py-scroll-process-buffer t))
  1969.     (set-buffer pbuf)
  1970.     (goto-char (point-max))
  1971.     (move-marker (process-mark process) (point))
  1972.     (if (not (or py-this-is-emacs-19-p
  1973.          py-this-is-lucid-emacs-p))
  1974.     (move-marker last-input-start (point))) ; muck w/ shell-mode
  1975.     (funcall (process-filter process) process string)
  1976.     (if (not (or py-this-is-emacs-19-p
  1977.          py-this-is-lucid-emacs-p))
  1978.     (move-marker last-input-end (point))) ; muck w/ shell-mode
  1979.     (set-buffer cbuf))
  1980.   (sit-for 0))
  1981.  
  1982. (defun py-keep-region-active ()
  1983.   ;; do whatever is necessary to keep the region active in XEmacs.
  1984.   ;; Ignore byte-compiler warnings you might see.  Also note that
  1985.   ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
  1986.   ;; require us to take explicit action.
  1987.   (and (boundp 'zmacs-region-stays)
  1988.        (setq zmacs-region-stays t)))
  1989.  
  1990.  
  1991. (defconst py-version "2.30"
  1992.   "`python-mode' version number.")
  1993. (defconst py-help-address "python-mode@python.org"
  1994.   "Address accepting submission of bug reports.")
  1995.  
  1996. (defun py-version ()
  1997.   "Echo the current version of `python-mode' in the minibuffer."
  1998.   (interactive)
  1999.   (message "Using `python-mode' version %s" py-version)
  2000.   (py-keep-region-active))
  2001.  
  2002. ;; only works under Emacs 19
  2003. ;(eval-when-compile
  2004. ;  (require 'reporter))
  2005.  
  2006. (defun py-submit-bug-report (enhancement-p)
  2007.   "Submit via mail a bug report on `python-mode'.
  2008. With \\[universal-argument] just submit an enhancement request."
  2009.   (interactive
  2010.    (list (not (y-or-n-p
  2011.            "Is this a bug report? (hit `n' to send other comments) "))))
  2012.   (let ((reporter-prompt-for-summary-p (if enhancement-p
  2013.                        "(Very) brief summary: "
  2014.                      t)))
  2015.     (require 'reporter)
  2016.     (reporter-submit-bug-report
  2017.      py-help-address            ;address
  2018.      (concat "python-mode " py-version)    ;pkgname
  2019.      ;; varlist
  2020.      (if enhancement-p nil
  2021.        '(py-python-command
  2022.      py-indent-offset
  2023.      py-block-comment-prefix
  2024.      py-scroll-process-buffer
  2025.      py-temp-directory
  2026.      py-beep-if-tab-change))
  2027.      nil                ;pre-hooks
  2028.      nil                ;post-hooks
  2029.      "Dear Barry,")            ;salutation
  2030.     (if enhancement-p nil
  2031.       (set-mark (point))
  2032.       (insert 
  2033. "Please replace this text with a sufficiently large code sample\n\
  2034. and an exact recipe so that I can reproduce your problem.  Failure\n\
  2035. to do so may mean a greater delay in fixing your bug.\n\n")
  2036.       (exchange-point-and-mark)
  2037.       (py-keep-region-active))))
  2038.  
  2039.  
  2040. ;; arrange to kill temp files when Emacs exists
  2041. (if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
  2042.     (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
  2043.   ;; have to trust that other people are as respectful of our hook
  2044.   ;; fiddling as we are of theirs
  2045.   (if (boundp 'py-inherited-kill-emacs-hook)
  2046.       ;; we were loaded before -- trust others not to have screwed us
  2047.       ;; in the meantime (no choice, really)
  2048.       nil
  2049.     ;; else arrange for our hook to run theirs
  2050.     (setq py-inherited-kill-emacs-hook kill-emacs-hook)
  2051.     (setq kill-emacs-hook 'py-kill-emacs-hook)))
  2052.  
  2053.  
  2054.  
  2055. (provide 'python-mode)
  2056. ;;; python-mode.el ends here
  2057.